package com.hunantv.mglive.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.hunantv.mglive.R;
import com.hunantv.mglive.data.GiftShowViewDataModel;
import com.hunantv.mglive.utils.GlideRoundTransform;
import com.hunantv.mglive.utils.L;
import com.hunantv.mglive.utils.UIUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by QiuDa on 15/12/19.
 */
public class GiftShowView {
    private static final String TAG = "GiftShowView";
    private float displacement;
    private final int MAX_LIST_NUM = 200;
    private boolean mIsStartFirst;
    private boolean mIsStartSecond;
    private boolean mIsStartFirstDelay;
    private boolean mIsAnimLeft;
    private Context mContext;
    private RelativeLayout mViewGroup;
    private LayoutInflater mInflater;
    private List<GiftShowViewDataModel> mDataList = new ArrayList<>();
    private List<View> mView = new ArrayList<>();
    private long mAnimLeftChangeTime = 0;

    public GiftShowView(Context mContext, RelativeLayout viewGroup, boolean isAnimLeft) {
        this.mContext = mContext;
        this.mViewGroup = viewGroup;
        mInflater = LayoutInflater.from(mContext);
        mIsAnimLeft = isAnimLeft;
        if (mIsAnimLeft) {
            displacement = -0.04f;
        } else {
            displacement = 0.04f;
        }
    }

    private void showView(GiftShowViewDataModel dataModel, final boolean isFirst) {
        final View view = getView();
        if (view != null) {
            RelativeLayout.LayoutParams ps = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            if (isFirst) {
                ps.setMargins(0, 0, 0, 0);
            } else {
                ps.setMargins(0, (int) UIUtil.dip2px(mContext, 80), 0, 0);
            }
            view.setLayoutParams(ps);
        } else {
            if (isFirst) {
                mIsStartFirst = false;
            } else {
                mIsStartSecond = false;
            }
            return;
        }

        final GSViewHolder viewHolder = (GSViewHolder) view.getTag();

        setGiftAnimView(dataModel, viewHolder);

        mViewGroup.addView(view);

        AnimationSet animationSet = getAnimationSet1();

        final AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
        alphaAnimation.setDuration(300);
        alphaAnimation.setFillAfter(true);

        final TranslateAnimation translateAnimationImage = getImageTranslateAnim();

        final ScaleAnimation scaleAnimationNum = new ScaleAnimation(1.7f, 1f, 1.7f, 1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        scaleAnimationNum.setDuration(300);
        scaleAnimationNum.setFillAfter(true);

        final AnimationSet animationSetAll = getVieAnimationSet();

        animationSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                viewHolder.mHolderView.llInfo.startAnimation(alphaAnimation);
                viewHolder.mHolderGiftImg.llImge.startAnimation(translateAnimationImage);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        translateAnimationImage.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                viewHolder.mHolderView.llNum.startAnimation(scaleAnimationNum);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        scaleAnimationNum.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                view.startAnimation(animationSetAll);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        animationSetAll.setAnimationListener(new Animation.AnimationListener() {
                                                 @Override
                                                 public void onAnimationStart(Animation animation) {
                                                 }

                                                 @Override
                                                 public void onAnimationEnd(Animation animation) {
                                                     new Handler().post(new Runnable() {
                                                         @Override
                                                         public void run() {
                                                             viewHolder.mHolderView.llInfo.clearAnimation();
                                                             viewHolder.mHolderGiftImg.llImge.clearAnimation();
                                                             viewHolder.mHolderView.llNum.clearAnimation();
                                                             view.clearAnimation();
                                                             synchronized (mDataList) {
                                                                 mViewGroup.removeView(view);
                                                                 //左右动画切换的2秒内不缓存
                                                                 if (System.currentTimeMillis() - mAnimLeftChangeTime > 2000) {
                                                                     mView.add(view);
                                                                 }

                                                                 if (isFirst) {
                                                                     mIsStartFirst = false;
                                                                 } else {
                                                                     mIsStartSecond = false;
                                                                 }

                                                                 showNext();
                                                             }
                                                         }
                                                     });
                                                 }

                                                 @Override
                                                 public void onAnimationRepeat(Animation animation) {

                                                 }
                                             }

        );

        view.startAnimation(animationSet);
    }

    private View getView() {
        View view;
        GSViewHolder viewHolder;
        synchronized (mDataList) {
            if (!mView.isEmpty()) {
                view = mView.get(0);
                mView.remove(0);
            } else {
                if (mIsAnimLeft) {
                    view = mInflater.inflate(R.layout.gift_show_view_left_layout, null);
                } else {
                    view = mInflater.inflate(R.layout.gift_show_view_right_layout, null);
                }
                viewHolder = new GSViewHolder();
                viewHolder.mHolderView = new ViewHodlerItem();
                viewHolder.mHolderGiftImg = new ViewHodlerItem();

                viewHolder.view = view.findViewById(R.id.icv_gift_show_view);
                if (mIsAnimLeft) {
                    viewHolder.view.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.gift_show_view_left_bg));
                } else {
                    viewHolder.view.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.gift_show_view_right_bg));
                }
                viewHolder.vGiftImage = view.findViewById(R.id.icv_gift_show_view_gitf_img);

                initViewHolder(viewHolder.vGiftImage, viewHolder.mHolderGiftImg);
                initViewHolder(viewHolder.view, viewHolder.mHolderView);
                view.setTag(viewHolder);
            }
        }
        return view;
    }


    private void initViewHolder(View view, ViewHodlerItem viewHodlerItem) {
        viewHodlerItem.ivIcon = (ImageView) view.findViewById(R.id.iv_gift_show_view_icon);
        viewHodlerItem.tvUserName = (TextView) view.findViewById(R.id.tv_gift_show_view_user_name);
        viewHodlerItem.tvStarName = (TextView) view.findViewById(R.id.tv_gift_show_view_star_name);
        viewHodlerItem.ivGiftImg = (ImageView) view.findViewById(R.id.iv_gift_show_gift_img);
        viewHodlerItem.tvX = (TextView) view.findViewById(R.id.tv_gift_show_view_x);
        viewHodlerItem.tvNum = (TextView) view.findViewById(R.id.tv_gift_show_view_num);
        viewHodlerItem.llInfo = (LinearLayout) view.findViewById(R.id.ll_gift_show_view_info);
        viewHodlerItem.llNum = (LinearLayout) view.findViewById(R.id.ll_gift_show_view_num);
        viewHodlerItem.llImge = (LinearLayout) view.findViewById(R.id.ll_gift_show_view_img);
    }

    private void setGiftAnimView(GiftShowViewDataModel dataModel, GSViewHolder viewHolder) {
        if (dataModel != null) {
            setView(dataModel, viewHolder.mHolderGiftImg, true);
            setView(dataModel, viewHolder.mHolderView, false);
            setTextView(viewHolder.mHolderView);
        }

        setGiftImageDispaly(viewHolder.mHolderGiftImg);
    }


    private void setView(GiftShowViewDataModel dataModel, ViewHodlerItem viewItem,
                         boolean setImage) {
        if (Util.isOnMainThread() && !((Activity) mContext).isFinishing()) {
            Glide.with(mContext).load(dataModel.getIcon()).transform(new GlideRoundTransform(mContext, R.dimen.height_30dp)).into(viewItem.ivIcon);
            viewItem.tvUserName.setText(dataModel.getUserName());
            viewItem.tvStarName.setText(mContext.getString(R.string.gift_give, dataModel.getStarName()));
            if (setImage) {
                Glide.with(mContext).load(dataModel.getImage()).into(viewItem.ivGiftImg);
            }
        }
        viewItem.tvNum.setText(dataModel.getNum() + "");
    }


    private void setTextView(ViewHodlerItem viewItem) {
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        viewItem.tvNum.measure(w, h);
        int viewHeight = viewItem.tvNum.getMeasuredHeight();

        Shader shaderNum = new LinearGradient(0, 0, 0, viewHeight, Color.WHITE, Color.YELLOW, Shader.TileMode.CLAMP);
        viewItem.tvNum.getPaint().setShader(shaderNum);


        w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        viewItem.tvX.measure(w, h);
        viewHeight = viewItem.tvX.getMeasuredHeight();

        Shader shaderX = new LinearGradient(0, 0, 0, viewHeight, Color.WHITE, Color.YELLOW, Shader.TileMode.CLAMP);
        viewItem.tvX.getPaint().setShader(shaderX);
    }

    private void setGiftImageDispaly(ViewHodlerItem viewItem) {
//        ViewGroup.LayoutParams ps = viewItem.llImge.getLayoutParams();
//        ps.height = ps.width = mContext.getResources().getDimensionPixelSize(R.dimen.height_50dp);
    }


    private AnimationSet getAnimationSet1() {
        AnimationSet animationSet = new AnimationSet(true);
        if (mIsAnimLeft) {
            TranslateAnimation translateAnimation =
                    new TranslateAnimation(Animation.RELATIVE_TO_SELF, -5, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
            translateAnimation.setDuration(300);
            animationSet.addAnimation(translateAnimation);

            TranslateAnimation translateAnimationback =
                    new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, displacement, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
            translateAnimationback.setDuration(300);
            translateAnimationback.setStartOffset(300);
            animationSet.addAnimation(translateAnimationback);
            animationSet.setFillBefore(true);
            animationSet.setFillAfter(true);
        } else {
            TranslateAnimation translateAnimation =
                    new TranslateAnimation(Animation.RELATIVE_TO_SELF, 1, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
            translateAnimation.setDuration(300);
            animationSet.addAnimation(translateAnimation);
            TranslateAnimation translateAnimationback =
                    new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, displacement, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
            translateAnimationback.setDuration(300);
            translateAnimationback.setStartOffset(300);
            animationSet.addAnimation(translateAnimationback);

            animationSet.setFillBefore(true);
            animationSet.setFillAfter(true);
        }
        return animationSet;
    }


    private TranslateAnimation getImageTranslateAnim() {
        TranslateAnimation translateAnimationImage;
        if (mIsAnimLeft) {
            translateAnimationImage = new TranslateAnimation(Animation.RELATIVE_TO_SELF, -1, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
            translateAnimationImage.setDuration(300);
            translateAnimationImage.setFillAfter(true);
        } else {
            translateAnimationImage = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 2, Animation.RELATIVE_TO_SELF, 0f, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 0);
            translateAnimationImage.setDuration(300);
            translateAnimationImage.setFillAfter(true);
        }
        return translateAnimationImage;
    }


    private AnimationSet getVieAnimationSet() {
        AnimationSet animationSetAll = new AnimationSet(true);
        TranslateAnimation translateAnimationAll;
        AlphaAnimation alphaAnimationAll;
        if (mIsAnimLeft) {
            translateAnimationAll = new TranslateAnimation(Animation.RELATIVE_TO_SELF, displacement, Animation.RELATIVE_TO_SELF, displacement, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1f);
        } else {
            translateAnimationAll = new TranslateAnimation(Animation.RELATIVE_TO_SELF, displacement, Animation.RELATIVE_TO_SELF, displacement, Animation.RELATIVE_TO_SELF, 0, Animation.RELATIVE_TO_SELF, 1);
        }

        translateAnimationAll.setDuration(700);
        translateAnimationAll.setFillAfter(true);

        alphaAnimationAll = new AlphaAnimation(1, 0);
        alphaAnimationAll.setDuration(700);
        alphaAnimationAll.setFillAfter(true);

        animationSetAll.addAnimation(translateAnimationAll);
        animationSetAll.addAnimation(alphaAnimationAll);
        animationSetAll.setFillAfter(true);
        return animationSetAll;
    }


    private synchronized void showNext() {
        GiftShowViewDataModel model = null;
        if (mDataList.size() > 0) {
            model = mDataList.get(0);
        }
        if (model != null) {
            if (!mIsStartFirst) {
                mDataList.remove(model);
                showViewFirst(model);
            } else if (!mIsStartSecond && !mIsStartFirstDelay) {
                mDataList.remove(model);
                showViewSecond(model);
            }
        }
    }

    private void showViewFirst(GiftShowViewDataModel dataModel) {
        mIsStartFirst = true;
        mIsStartFirstDelay = true;
        new Handler().postDelayed(new Runnable() {
                                      @Override
                                      public void run() {
                                          synchronized (mDataList) {
                                              mIsStartFirstDelay = false;
                                              showNext();
                                          }
                                      }
                                  }

                , 300);

        showView(dataModel, true);
    }


    private void showViewSecond(GiftShowViewDataModel dataModel) {
        mIsStartSecond = true;
        showView(dataModel, false);
    }


    public void show(GiftShowViewDataModel dataModel) {
        synchronized (mDataList) {
            if (!mIsStartFirst && mDataList.isEmpty()) {
                showViewFirst(dataModel);
            } else if (!mIsStartSecond && !mIsStartFirstDelay && mDataList.isEmpty()) {
                showViewSecond(dataModel);
            } else {
                if (mDataList.size() < MAX_LIST_NUM) {
                    mDataList.add(dataModel);
                }
            }
        }
    }

    public void changeGiftSetting(RelativeLayout viewGroup, boolean isAnimLeft) {
        synchronized (mDataList) {
            mView.clear();
            mViewGroup.removeAllViews();
            mViewGroup = viewGroup;
            mIsAnimLeft = isAnimLeft;
        }
    }

    public void setIsAnimLeft(boolean isAnimLeft) {
        mAnimLeftChangeTime = System.currentTimeMillis();
        synchronized (mDataList) {
            this.mIsAnimLeft = isAnimLeft;
            if (mIsAnimLeft) {
                displacement = -0.04f;
            } else {
                displacement = 0.04f;
            }
            removeAllAnim();
            mIsStartFirst = false;
            mIsStartSecond = false;
            mIsStartFirstDelay = false;
            mView.clear();
            mDataList.clear();
        }

    }

    private void removeAllAnim(){
        if(mViewGroup != null)
        {
            int count = mViewGroup.getChildCount();
            for(int i=count-1;i>=0;i--){
                View view = mViewGroup.getChildAt(i);
                if(view != null)
                {
                    view.clearAnimation();
                    mViewGroup.removeView(view);
                }
            }
        }
    }

    class GSViewHolder {
        View view;
        View vGiftImage;
        ViewHodlerItem mHolderGiftImg;
        ViewHodlerItem mHolderView;
    }

    class ViewHodlerItem {
        ImageView ivIcon;
        TextView tvUserName;
        TextView tvStarName;
        ImageView ivGiftImg;
        TextView tvX;
        TextView tvNum;
        LinearLayout llInfo;
        LinearLayout llNum;
        LinearLayout llImge;
    }

}
